//
//  MD2Entity.m
//  CompGraf2
//
//  Created by Juan Niosi on 04/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MD2Entity.h"

@implementation MD2Entity
@synthesize model;

- (id)init:(MD2Model *)md2model withAnim:(NSString *)firstAnim;
{
    self = [super init];
    if (self) {
        self.model = md2model;
        animName = firstAnim;
        animLoop = true;
        [self playAnim];
    }
    
    return self;
}

- (BOOL)playAnim
{
    if (![model hasAnim:animName])
    {
        isPlaying = false;
        return false;
    }
    animTime = 0.0f;
    isPlaying = true;
    for (Entity *child in children)
    {
        if ([child class] == [MD2Entity class])
        {
            MD2Entity *md2 = (MD2Entity*)child;
            [md2 playAnim:animName loop:animLoop];
        }
    }
    return true;
}

- (BOOL)playAnim:(NSString *)anim loop:(BOOL)doLoop
{
    animName = anim;
    if (![model hasAnim:animName])
    {
        isPlaying = false;
        return false;
    }
    for (Entity *child in children)
    {
        if ([child class] == [MD2Entity class])
        {
            MD2Entity *md2 = (MD2Entity*)child;
            [md2 playAnim:animName loop:animLoop];
        }
    }
    animLoop = doLoop;
    animTime = 0.0f;
    isPlaying = true;
    return true;
}

- (BOOL)stopAnim
{
    if (!isPlaying)
        return false;
    
    isPlaying = false;
    for (Entity *child in children)
    {
        if ([child class] == [MD2Entity class])
        {
            MD2Entity *md2 = (MD2Entity*)child;
            [md2 stopAnim];
        }
    }
    return true;
}

- (void)update:(float)deltaTime;
{
    [super update:deltaTime];
    if (isPlaying)
    {
        animTime += deltaTime;
    }
    
}

- (void)draw:(Engine *)engine :(Camera *)cam
{
    if ([cam isVisible:model.bounds])
    {
        [self applyTransform:engine];
        
        float frame = animTime * ANIM_FPS;
        if (![model draw:engine withAnim:animName atTime:frame looping:animLoop] && isPlaying)
        {
            isPlaying = false;
        }

        for (Entity *child in children)
            [child draw:engine :cam];
        
        [self resetTransform:engine];
    }
}

- (void)dealloc
{
    [model release];
    [animName release];
    [super release];
}
@end
